<template>
  <div class="recognition-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>识别记录列表</span>
          <div>
            <el-button type="primary" @click="handleExport">导出记录</el-button>
            <el-button type="danger" @click="handleBatchDelete"
              >批量删除</el-button
            >
          </div>
        </div>
      </template>

      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="用户账号">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
            />
          </el-form-item>
          <el-form-item label="用户ID">
            <el-input
              v-model="queryParams.user_id"
              placeholder="请输入用户ID"
              clearable
            />
          </el-form-item>
          <el-form-item label="激活码">
            <el-input
              v-model="queryParams.activation_code"
              placeholder="请输入激活码"
              clearable
            />
          </el-form-item>
          <el-form-item label="识别类型">
            <el-select
              v-model="queryParams.recognition_type"
              placeholder="请选择类型"
              clearable
            >
              <el-option label="人脸识别" value="face" />
              <el-option label="身份证" value="id_card" />
              <el-option label="驾驶证" value="drive_license" />
            </el-select>
          </el-form-item>
          <el-form-item label="识别结果">
            <el-select
              v-model="queryParams.recognition_result"
              placeholder="请选择结果"
              clearable
            >
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="statistics-overview" v-if="statistics.total_count">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-title">总识别次数</div>
              <div class="stat-value">{{ statistics.total_count }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-title">成功次数</div>
              <div class="stat-value success">
                {{ statistics.success_count }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-title">失败次数</div>
              <div class="stat-value failed">{{ statistics.failed_count }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-title">成功率</div>
              <div class="stat-value">{{ statistics.success_rate }}%</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-table
        v-loading="loading"
        :data="recordList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户账号" width="120" />
        <el-table-column prop="user_id" label="用户ID" width="120" />
        <el-table-column prop="photo_url" label="识别图片" width="120">
          <template #default="scope">
            <div v-if="scope.row.photo_url" class="image-container">
              <el-image
                :src="getDirectUrl(scope.row.photo_url)"
                class="thumbnail-image"
                :preview-src-list="[getDirectUrl(scope.row.photo_url)]"
                preview-teleported
                fit="cover"
                @error="handleImageError"
              />
            </div>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="recognition_type" label="识别类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.recognition_type)">
              {{ getRecognitionTypeName(scope.row.recognition_type) }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="recognition_result" label="识别结果" width="100">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.recognition_result === 'success'
                  ? 'success'
                  : 'danger'
              "
            >
              {{ scope.row.recognition_result === "success" ? "成功" : "失败" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="success_rate" label="识别率" width="100">
          <template #default="scope"> {{ scope.row.success_rate }}% </template>
        </el-table-column>
        <!-- <el-table-column
          prop="location"
          label="地理位置"
          width="150"
          show-overflow-tooltip
        /> -->
        <el-table-column
          prop="device_info"
          label="设备信息"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="created_at" label="识别时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import {
  getRecognitionRecords,
  deleteRecognition,
  batchDeleteRecognitions,
  exportRecognitionRecords,
  getRecognitionStatistics,
} from "@/api/recognition-records";

const router = useRouter();
const loading = ref(false);
const recordList = ref([]);
const total = ref(0);
const dateRange = ref([]);
const selectedRows = ref([]);
const statistics = ref({
  total_count: 0,
  success_count: 0,
  failed_count: 0,
  success_rate: 0,
});

const queryParams = reactive({
  page: 1,
  limit: 10,
  username: "",
  user_id: "",
  activation_code: "",
  recognition_type: "",
  recognition_result: "",
  start_date: "",
  end_date: "",
});

// 获取识别记录列表
const getList = async () => {
  loading.value = true;
  try {
    // 创建查询参数的副本，并确保激活码参数使用正确的名称
    const params = { ...queryParams };

    // 将activation_code转换为code参数(如果有值)
    if (params.activation_code && params.activation_code.trim() !== "") {
      params.code = params.activation_code;
      // 可选：保留原参数作为备用
      // delete params.activation_code;
    }

    console.log("发送查询参数:", params);

    const res = await getRecognitionRecords(params);
    if (res.code === 0) {
      console.log("获取到识别记录:", res.data);
      recordList.value = res.data.items;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取识别记录失败");
    }
  } catch (error) {
    console.error("获取识别记录失败", error);
    ElMessage.error("获取识别记录失败");
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    // 使用与列表查询相同的参数处理方式
    const statisticsParams = {
      user_id: queryParams.user_id,
      username: queryParams.username,
      recognition_type: queryParams.recognition_type,
      recognition_result: queryParams.recognition_result,
      start_date: queryParams.start_date,
      end_date: queryParams.end_date,
    };

    // 处理激活码参数
    if (
      queryParams.activation_code &&
      queryParams.activation_code.trim() !== ""
    ) {
      statisticsParams.code = queryParams.activation_code;
    }

    console.log("发送统计查询参数:", statisticsParams);

    const res = await getRecognitionStatistics(statisticsParams);
    if (res.code === 0) {
      console.log("获取到统计数据:", res.data);
      statistics.value = res.data;
    }
  } catch (error) {
    console.error("获取统计数据失败", error);
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
  getStatistics();
};

// 重置查询
const resetQuery = () => {
  queryParams.username = "";
  queryParams.user_id = "";
  queryParams.activation_code = "";
  queryParams.recognition_type = "";
  queryParams.recognition_result = "";
  queryParams.start_date = "";
  queryParams.end_date = "";
  dateRange.value = [];
  handleQuery();
};

// 日期范围变化
const handleDateChange = (val) => {
  if (val) {
    queryParams.start_date = val[0];
    queryParams.end_date = val[1];
  } else {
    queryParams.start_date = "";
    queryParams.end_date = "";
  }
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val;
  queryParams.page = 1;
  getList();
};

// 处理表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 查看详情
const handleDetail = (row) => {
  // router.push(`/recognition/detail/${row.id}`);

  const url = `${location.origin}/#/recognition/detail/${row.id}`;
  window.open(url, "_blank");
};

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认要删除该识别记录吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteRecognition(row.id);
        if (res.code === 0) {
          ElMessage.success("删除成功");
          getList();
          getStatistics();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  const ids = selectedRows.value.map((item) => item.id);

  ElMessageBox.confirm(`确认要删除选中的 ${ids.length} 条记录吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await batchDeleteRecognitions(ids);
        if (res.code === 0) {
          ElMessage.success("批量删除成功");
          getList();
          getStatistics();
        } else {
          ElMessage.error(res.message || "批量删除失败");
        }
      } catch (error) {
        console.error("批量删除失败", error);
        ElMessage.error("批量删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 导出记录
const handleExport = () => {
  ElMessageBox.confirm("确认要导出识别记录吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(async () => {
      try {
        // 使用当前查询条件，保持参数一致性
        const exportParams = { ...queryParams };
        // 移除分页参数
        delete exportParams.page;
        delete exportParams.limit;

        // 处理激活码参数
        if (
          exportParams.activation_code &&
          exportParams.activation_code.trim() !== ""
        ) {
          exportParams.code = exportParams.activation_code;
        }

        console.log("发送导出查询参数:", exportParams);

        const res = await exportRecognitionRecords(exportParams);

        // 创建下载链接
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = `recognition_records_${new Date().getTime()}.xlsx`;
        link.click();
        URL.revokeObjectURL(link.href);

        ElMessage.success("导出成功");
      } catch (error) {
        console.error("导出失败", error);
        ElMessage.error("导出失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取识别类型名称
const getRecognitionTypeName = (type) => {
  const typeMap = {
    face: "人脸识别",
    id_card: "身份证",
    drive_license: "驾驶证",
  };
  return typeMap[type] || "未知";
};

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    face: "primary",
    id_card: "success",
    drive_license: "warning",
  };
  return typeMap[type] || "";
};

// 打开直接URL
const openDirectUrl = (url) => {
  if (!url) return;

  try {
    // 处理特殊URL：腾讯云COS
    let processedUrl = url;

    // 确保URL使用https
    if (processedUrl.startsWith("http:")) {
      processedUrl = processedUrl.replace("http:", "https:");
    } else if (!processedUrl.startsWith("http")) {
      processedUrl = "https://" + processedUrl;
    }

    // 处理腾讯云COS链接特殊情况
    if (
      processedUrl.includes("cos.") &&
      processedUrl.includes("myqcloud.com")
    ) {
      console.log("检测到腾讯云COS链接");
    }

    // 日志记录
    console.log("处理后的URL:", processedUrl);

    // 打开新标签页
    window.open(processedUrl, "_blank");
  } catch (error) {
    console.error("打开URL时出错:", error, url);
    ElMessage.error("打开图片链接失败");
  }
};

// 处理图片错误
const handleImageError = (event) => {
  console.log("图片加载失败:", event);
  // 显示错误后的按钮备用方案
  const el = event.target;
  if (el && el.parentElement) {
    // 隐藏出错的图片
    el.style.display = "none";

    // 创建按钮作为备用
    const container = el.parentElement.parentElement;
    if (container) {
      const button = document.createElement("el-button");
      button.innerHTML =
        '<span><i class="el-icon-picture-outline"></i> 查看图片</span>';
      button.className =
        "el-button el-button--primary el-button--small is-plain";
      button.style.margin = "5px";
      button.onclick = () => {
        const url = el.getAttribute("src");
        if (url) openDirectUrl(url);
      };
      container.appendChild(button);
    }
  }
};

// 获取直接URL
const getDirectUrl = (url) => {
  if (!url) return "";

  // 确保URL使用https
  if (url.startsWith("http:")) {
    url = url.replace("http:", "https:");
  } else if (!url.startsWith("http")) {
    url = "https://" + url;
  }

  return url;
};

onMounted(() => {
  getList();
  getStatistics();
});
</script>

<style scoped>
.recognition-list-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.failed {
  color: #f56c6c;
}

.el-table {
  flex: 1;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容样式优化 */
:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  line-height: 1.5;
}

/* 按钮样式调整 */
.card-header .el-button {
  padding: 9px 16px;
}

.el-table .el-button {
  padding: 6px 12px;
  margin: 0 4px;
}

.el-tag {
  font-weight: 500;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.error-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.image-container {
  width: 100%;
  text-align: center;
  padding: 5px;
}

.thumbnail-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
